﻿#region

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;
using Tateeda.ClinicalStudy.Base.Modules.Common.Enumeration;
using Tateeda.ClinicalStudy.Base.Modules.Infrastructure.Interfaces.Services;
using Tateeda.ClinicalStudy.Base.Modules.Models.StudyForm;
using Tateeda.ClinicalStudy.Base.Modules.Models.StudyVisit;
using Tateeda.ClinicalStudy.Base.Web.Common;

#endregion

#region - Legal -

///<legal>
/// Copyright © 2011, Tateeda Media Network
/// All rights reserved. http://tateeda.com
///
/// Redistribution and use in source and binary forms, with or without
/// modification, are permitted provided that the following conditions
/// are met:
///
/// - Redistributions of source code must retain the above copyright
/// notice, this list of conditions and the following disclaimer.
///
/// - Neither the name of the Tateeda Media Network, nor the names of its
/// contributors may be used to endorse or promote products
/// derived from this software without specific prior written
/// permission.
///
/// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
/// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
/// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
/// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
/// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
/// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES INCLUDING,
/// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
/// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
/// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
/// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
/// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
/// POSSIBILITY OF SUCH DAMAGE.
///</legal>

#endregion - Legal -

namespace Tateeda.ClinicalStudy.Base.Web.Controllers {

    public class MatrixController : Controller {
        private readonly IMatrixService _service;

        public MatrixController(IMatrixService service) {
            _service = service;
        }

        #region - Actions -

        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult Index() {
            return View();
        }

        [OutputCache(Duration = 30)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult Visits() {
            var visits = _service.GetVisits();
            return View(visits);
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult VisitCreate() {
            return View();
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult VisitEdit(int id) {
            return View(_service.GetVisit(id));
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult VisitEdit(VisitModel visit) {
            try {
                _service.UpdateVisit(visit);
                return RedirectToAction("Visits");
            } catch {
                return View(visit);
            }
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        [HttpPost]
        public ActionResult VisitCreate(VisitModel visit) {
            try {
                visit.CreatedOn = DateTime.UtcNow;
                visit.UpdatedOn = DateTime.UtcNow;
                _service.CreateVisit(visit);
                return RedirectToAction("Visits");
            } catch {
                return View(visit);
            }
        }

        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult VisitDelete(int id) {
            _service.DeleteVisit(id);
            return RedirectToAction("Visits");
        }

        [OutputCache(Duration = 30)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult MatrixMap() {
            ViewBag.MatrixHTML = _service.MatrixMappingHTML();
            return View();
        }

        [OutputCache(Duration = 30)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult MatrixMappingMgr() {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [ValidateAntiForgeryToken]
        public ActionResult VisitFormsOrder() {
            return View();
        }

        [Authorize(Roles = "Admin")]
        [ValidateAntiForgeryToken]
        public void UpdateVisitMapping(int? visitId, string ids) {
            if (visitId == null) throw new Exception("Visit Must be selected");

            var stringIds = ids.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var formIds = stringIds.Select(int.Parse).ToList();
            _service.CreateVisitToFormMap(visitId.Value, formIds.ToArray());
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult SubmitSortOrderUpdate(FormCollection form) {
            int visitId = int.Parse(form["VisitId"]);
            var formsId = new Dictionary<int, int>();

            foreach (var frmId in form.AllKeys) {
                int id;
                int.TryParse(frmId, out id);
                if (id > 0) {
                    int order;
                    int.TryParse(form[frmId], out order);
                    formsId.Add(id, order);
                }
            }
            _service.UpdateVisitFormsOrder(visitId, formsId);
            return RedirectToAction("Index");
        }

        #endregion - Actions -

        #region - JSON Results -

        /// <summary>
        ///   Gets the active forms.
        /// </summary>
        /// <param name = "formType">Type of the form (Form or Lab).</param>
        /// <returns></returns>
        [OutputCache(Duration = 30)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdmin)]
        public JsonResult GetActiveForms(string formType) {
            ICollection<StudyFormModel> forms = null;
            switch (formType) {
                case "Form":
                    forms = _service.GetActiveForms(StudyFormType.DynamicForm);
                    break;
                case "Lab":
                    forms = _service.GetActiveForms(StudyFormType.DynamicLab);
                    break;
            }

            if (forms != null) {
                var models =
                    forms.Select(
                        form => new StudyFormModel { FormId = form.FormId, Name = form.Name, SortOrder = form.SortOrder }).
                        ToList();

                return Json(models);
            }

            return Json("");
        }

        [OutputCache(Duration = 30)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdmin)]
        public JsonResult GetVisitMappedForms(int visitId) {
            var forms = _service.GetVisitMappedForms(visitId, StudyFormType.DynamicForm);
            var models =
                forms.Select(
                    form => new StudyFormModel { FormId = form.FormId, Name = form.Name, SortOrder = form.SortOrder }).
                    ToList();

            return Json(models);
        }

        [OutputCache(Duration = 30)]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = Constants.RoleAdmin)]
        public JsonResult GetVisitMappedLabs(int visitId) {
            var forms = _service.GetVisitMappedForms(visitId, StudyFormType.DynamicLab);
            var models =
                forms.Select(
                    form => new StudyFormModel { FormId = form.FormId, Name = form.Name, SortOrder = form.SortOrder }).
                    ToList();

            return Json(models);
        }

        #endregion - JSON Results -
    }
}